const express = require('express');
const router = express.Router();
const { authenticateToken, authenticateAdmin } = require('../middleware/auth');
const ResponseHelper = require('../utils/response');
const ContactViewPrisma = require('../models/ContactViewPrisma');
const UserPrisma = require('../models/UserPrisma');
const Validator = require('../utils/validator');

/**
 * 获取用户联系方式（需要权限检查和收费）
 * GET /api/v1/contact-view/user/:userId
 */
router.get('/user/:userId', authenticateToken, async (req, res) => {
  try {
    const { userId } = req.params;
    const viewerId = req.user.id;
    
    // 不能查看自己的联系方式
    if (viewerId.toString() === userId) {
      return ResponseHelper.error(res, '不能查看自己的联系方式', 400);
    }
    
    // 检查目标用户是否存在
    const targetUser = await UserPrisma.findById(userId);
    if (!targetUser) {
      return ResponseHelper.notFound(res, '用户不存在');
    }
    
    // 检查目标用户是否有联系方式
    if (!targetUser.phone_number && !targetUser.wechat_id) {
      return ResponseHelper.error(res, '该用户未设置联系方式', 400);
    }
    
    // 获取当前月份
    const currentMonth = new Date().toISOString().slice(0, 7); // YYYY-MM

    // 获取用户信息，检查购买的查看次数
    const viewerUser = await UserPrisma.findById(viewerId);
    if (!viewerUser) {
      return ResponseHelper.unauthorized(res, '用户不存在');
    }

    // 检查免费查看次数
    const freeViewCheck = await ContactViewPrisma.checkFreeViewAvailability(viewerId, currentMonth);
    const pricePerView = parseFloat(await ContactViewPrisma.getConfig('price_per_view') || '1.00');

    let isPaid = false;
    let cost = 0;
    let useCredits = false;

    // 优先级：免费次数 > 购买的次数 > 付费查看
    if (freeViewCheck.canViewFree) {
      // 优先使用免费次数
      useCredits = false;
      isPaid = false;
      cost = 0;
    } else if (viewerUser.contact_view_credits > 0) {
      // 免费次数用完后，使用购买的查看次数
      useCredits = true;
      isPaid = false;
      cost = 0;
    } else {
      // 需要付费查看
      isPaid = true;
      cost = pricePerView;

      // 这里可以添加支付逻辑
      // 暂时先记录，实际项目中需要集成支付系统
    }

    // 如果使用购买的次数，先扣减
    if (useCredits) {
      try {
        await UserPrisma.reduceContactViewCredits(viewerId, 1);
      } catch (error) {
        return ResponseHelper.error(res, '查看次数不足', 400);
      }
    }

    // 记录查看行为
    await ContactViewPrisma.recordView(viewerId, userId, currentMonth, isPaid, cost);

    // 重新获取用户信息以获取最新的查看次数
    const updatedUser = await UserPrisma.findById(viewerId);

    ResponseHelper.success(res, {
      phone_number: targetUser.phone_number,
      wechat_id: targetUser.wechat_id,
      user_info: {
        id: targetUser.id.toString(),
        nickname: targetUser.nickname,
        avatar_url: targetUser.avatar_url
      },
      is_free: !isPaid,
      cost: cost,
      used_credits: useCredits,
      remaining_credits: updatedUser ? updatedUser.contact_view_credits : 0,
      remaining_free_views: Math.max(0, freeViewCheck.maxFreeViews - freeViewCheck.usedFreeViews - (isPaid || useCredits ? 0 : 1))
    }, '获取联系方式成功');
    
  } catch (error) {
    console.error('获取联系方式错误:', error);
    ResponseHelper.serverError(res, '获取联系方式失败', error);
  }
});

/**
 * 检查查看联系方式的权限和费用
 * GET /api/v1/contact-view/check/:userId
 */
router.get('/check/:userId', authenticateToken, async (req, res) => {
  try {
    const { userId } = req.params;
    const viewerId = req.user.id;
    
    // 不能查看自己的联系方式
    if (viewerId.toString() === userId) {
      return ResponseHelper.error(res, '不能查看自己的联系方式', 400);
    }
    
    // 检查目标用户是否存在
    const targetUser = await UserPrisma.findById(userId);
    if (!targetUser) {
      return ResponseHelper.notFound(res, '用户不存在');
    }
    
    // 检查目标用户是否有联系方式
    if (!targetUser.phone_number && !targetUser.wechat_id) {
      return ResponseHelper.error(res, '该用户未设置联系方式', 400);
    }
    
    // 获取当前月份
    const currentMonth = new Date().toISOString().slice(0, 7); // YYYY-MM

    // 获取用户信息，检查购买的查看次数
    const viewerUser = await UserPrisma.findById(viewerId);
    if (!viewerUser) {
      return ResponseHelper.unauthorized(res, '用户不存在');
    }

    // 检查免费查看次数
    const freeViewCheck = await ContactViewPrisma.checkFreeViewAvailability(viewerId, currentMonth);
    const pricePerView = parseFloat(await ContactViewPrisma.getConfig('price_per_view') || '1.00');

    // 优先级：免费次数 > 购买的次数 > 付费查看
    if (freeViewCheck.canViewFree) {
      // 优先使用免费次数
      ResponseHelper.success(res, {
        can_view: true,
        is_free: true,
        cost: 0,
        remaining_credits: viewerUser.contact_view_credits,
        remaining_free_views: freeViewCheck.maxFreeViews - freeViewCheck.usedFreeViews,
        message: `本月还可免费查看 ${freeViewCheck.maxFreeViews - freeViewCheck.usedFreeViews} 次`
      }, '检查成功');
    } else if (viewerUser.contact_view_credits > 0) {
      // 免费次数用完后，使用购买的查看次数
      ResponseHelper.success(res, {
        can_view: true,
        is_free: true, // 从用户角度看仍然是"免费"的，不需要额外付费
        cost: 0,
        remaining_credits: viewerUser.contact_view_credits,
        remaining_free_views: 0, // 确保免费次数显示为0
        message: `您有 ${viewerUser.contact_view_credits} 次购买的查看次数`
      }, '检查成功');
    } else {
      // 需要付费查看
      ResponseHelper.success(res, {
        can_view: true,
        is_free: false,
        cost: pricePerView,
        remaining_credits: 0,
        remaining_free_views: 0,
        message: `本月免费次数已用完，查看需要支付 ${pricePerView} 元`
      }, '检查成功');
    }
    
  } catch (error) {
    console.error('检查联系方式查看权限错误:', error);
    ResponseHelper.serverError(res, '检查失败', error);
  }
});

/**
 * 获取用户的查看统计
 * GET /api/v1/contact-view/stats
 */
router.get('/stats', authenticateToken, async (req, res) => {
  try {
    const viewerId = req.user.id;
    const currentMonth = new Date().toISOString().slice(0, 7); // YYYY-MM
    
    // 获取当月统计
    const monthlyViewCount = await ContactViewPrisma.getMonthlyViewCount(viewerId, currentMonth);
    const monthlyFreeViewCount = await ContactViewPrisma.getMonthlyFreeViewCount(viewerId, currentMonth);
    const freeViewCheck = await ContactViewPrisma.checkFreeViewAvailability(viewerId, currentMonth);
    
    ResponseHelper.success(res, {
      current_month: currentMonth,
      total_views: monthlyViewCount,
      free_views_used: monthlyFreeViewCount,
      paid_views: monthlyViewCount - monthlyFreeViewCount,
      remaining_free_views: Math.max(0, freeViewCheck.maxFreeViews - monthlyFreeViewCount),
      max_free_views: freeViewCheck.maxFreeViews
    }, '获取统计成功');
    
  } catch (error) {
    console.error('获取查看统计错误:', error);
    ResponseHelper.serverError(res, '获取统计失败', error);
  }
});

/**
 * 获取联系方式查看配置（公开接口,无需认证）
 * GET /api/v1/contact-view/config
 */
router.get('/config', async (req, res) => {
  try {
    const configs = await ContactViewPrisma.getAllConfigs();
    ResponseHelper.success(res, configs, '获取配置成功');
  } catch (error) {
    console.error('获取配置错误:', error);
    ResponseHelper.serverError(res, '获取配置失败', error);
  }
});

/**
 * 更新联系方式查看配置（管理员接口）
 * PUT /api/v1/contact-view/config
 */
router.put('/config', authenticateAdmin, async (req, res) => {
  try {
    const {
      enable_contact_view_fee,
      free_views_per_month,
      price_per_view,
      chat_message_mode,
      chat_free_daily_limit
    } = req.body;

    const updates = {};
    const errors = [];

    if (enable_contact_view_fee !== undefined) {
      updates.enable_contact_view_fee = enable_contact_view_fee ? '1' : '0';
    }
    if (free_views_per_month !== undefined) {
      updates.free_views_per_month = free_views_per_month.toString();
    }
    if (price_per_view !== undefined) {
      updates.price_per_view = price_per_view.toString();
    }
    if (chat_message_mode !== undefined) {
      const normalizedMode = typeof chat_message_mode === 'string'
        ? chat_message_mode.trim()
        : chat_message_mode;
      const modeError = Validator.validateEnum(
        normalizedMode,
        ['free', 'paid'],
        'chat_message_mode'
      );
      if (modeError) {
        errors.push(modeError);
      } else {
        updates.chat_message_mode = normalizedMode;
      }
    }
    if (chat_free_daily_limit !== undefined) {
      const parsedLimit = parseInt(chat_free_daily_limit, 10);
      if (Number.isNaN(parsedLimit) || parsedLimit < 0) {
        errors.push('chat_free_daily_limit 必须是大于或等于 0 的整数');
      } else {
        updates.chat_free_daily_limit = parsedLimit.toString();
      }
    }

    if (errors.length > 0) {
      return ResponseHelper.validationError(res, errors);
    }

    if (Object.keys(updates).length === 0) {
      return ResponseHelper.validationError(res, ['请提供需要更新的配置项']);
    }

    const updatedConfigs = await ContactViewPrisma.updateConfigs(updates);

    ResponseHelper.success(res, updatedConfigs, '更新配置成功');
  } catch (error) {
    console.error('更新配置错误:', error);
    ResponseHelper.serverError(res, '更新配置失败', error);
  }
});

module.exports = router;
